<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/22
 * Time: 15:12
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Join extends Model
{
    protected $table = 'join';
    //指定主键
    protected $primaryKey= 'id';
    protected $guarded = [];
    const STATUS_0 = 0; //状态0未中奖1已中奖
    const STATUS_1 = 1;
    public $timestamps = true;
    public function activity() {
        # Eloquent 假设外键会和上层模型的 id 字段（或者自定义的 $primaryKey）的值相匹配。否则，请
        return $this->hasOne('App\Models\Activity', 'id', 'activity_id');
    }

    public function user(){
        return $this->belongsTo('App\User','user_id','id');
    }

    public function address(){
        return $this->hasMany('App\Models\Address','id','address_id');
    }
    //批量更新
    public function updateBatch($multipleData = [])
    {
        try {
            if (empty($multipleData)) {
                throw new \Exception("数据不能为空");
            }
            $tableName = $this->getTable(); // 表名
            $firstRow  = current($multipleData);
            $updateColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);
            // 拼接sql语句
            $updateSql = "UPDATE `" . $tableName . "` SET ";
            $sets      = [];
            $bindings  = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn   = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings  = array_merge($bindings, $whereIn);
            $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }
    }


}